<template>
  <div id="code-editor" ref="codeEditorRef" style="min-height: 400px" />
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import { defineProps, onMounted, ref, toRaw, withDefaults } from "vue";
import { QuestionSubmitControllerService } from "../../api";
import store from "@/store";
import draculaTheme from "monaco-themes/themes/Dracula.json";

const codeEditorRef = ref();
const codeEditor = ref();

interface Props {
  value: string;
  handleChange: (v: string) => void;
  id: bigint;
  readonly: boolean;
  code: string;
}

const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  handleChange: (v: string) => {
    console.log(v);
  },
});

onMounted(async () => {
  monaco.editor.defineTheme("Dracula", {
    base: "vs-dark",
    inherit: true,
    rules: draculaTheme.rules,
    colors: draculaTheme.colors,
  });

  let loginUser = store.state.user.loginUser;
  const userId = loginUser.id ?? 0;
  const questionId = props.id as never;
  const code = props.code ?? "";
  const history = await QuestionSubmitControllerService.getHistoryCode(
    userId,
    questionId
  );
  if (!codeEditorRef.value) {
    return;
  }

  const tempValue =
    history.data == null || history.data == "" ? "#!bin/bash" : history.data;
  props.handleChange(tempValue);
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: code !== "" ? code : tempValue,
    language: "shell", // 硬编码设置为 bash
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    readOnly: props.readonly,
    theme: "Dracula",
    roundedSelection: false,
    folding: true,
    foldingHighlight: true,
    foldingStrategy: "indentation",
    showFoldingControls: "always",
    disableLayerHinting: true,
    emptySelectionClipboard: false,
    selectionClipboard: true,
    codeLens: true,
    scrollBeyondLastLine: true,
    accessibilitySupport: "off",
    lineNumbers: "on",
    lineNumbersMinChars: 5,
  });

  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});
</script>

<style scoped></style>
